﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using FimetContoDeposito.BLL.Facades;
using FimetContoDeposito.BLL.ResultSets;
using GrayParrot.Core;
using GrayParrot.Core.Json;
using GrayParrot.Web.Controls;
using GrayParrot.Web.Formly;
using GrayParrot.Web.Providers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Test.DAL;
using WebTest.Metadata;

namespace WebTest.Controllers
{
    public class EmployeeController : ApiController
    {
        [HttpGet]
        public string LoadFields_old()
        {
            string retValue = null;

            var m_fields = FormlyHelper.ToFormly<EmployeeMetadata>(typeof(EmployeeMetadata));

            retValue = FormlyHelper.Serialize(m_fields);

            //JsonSerializerSettings settings = new JsonSerializerSettings();
            //settings.ContractResolver = new NullToEmptyListResolver();
            //settings.Converters = new List<JsonConverter> { new Newtonsoft.Json.Converters.StringEnumConverter { CamelCaseText = false } };
            //settings.Formatting = Formatting.Indented;
            //settings.NullValueHandling = NullValueHandling.Ignore;

            //retValue = JsonConvert.SerializeObject(m_fields, settings);
            //retValue = FormlyHelper.Serialize(m_fields, new List<JsonConverter> { new EventsConverter() });

            return retValue;
        }

        [HttpGet]
        public string LoadFields()
        {
            string retValue = null;

            var m_fields = FormlyHelper.ToFormly<PalinsestoMetadata>(typeof(PalinsestoMetadata));

            //DateTime m_date = DateTime.Now.ToLocalTime();
            //DateTime m_date = new DateTime(2016, 12, 8, 20, 30, 00);
            //m_fields.DefaultValue<DateTime>("DataAvvenimento", m_date);

            retValue = FormlyHelper.Serialize(m_fields);
            //retValue = FormlyHelper.Serialize(m_fields, new List<JsonConverter> { new EventsConverter() });

            return retValue;
        }

        [HttpGet]
        public string LoadFields_old2()
        {
            string retValue = null;

            var m_fields = new FormlyFactory()
                   .AddInput("txtPalinsesto", "Palinsesto", "", "inserisci il palinsesto", false, true, 0, 0)
                   .AddInput("txtAvvenimento", "Avvenimento", "", "inserisci l'avvenimento", false, true, 0, 0)
                   .AddEvent(EventTypes.OnChange, "ChangeCallback")
                   .AddAddOn(Position.Right, "glyphicon glyphicon-ok", null, "CheckCallback")
                   .Create();

            //JsonSerializerSettings settings = new JsonSerializerSettings();
            //settings.ContractResolver = new NullToEmptyListResolver();
            //settings.Converters = new List<JsonConverter> { new Newtonsoft.Json.Converters.StringEnumConverter { CamelCaseText = false } };
            //settings.Formatting = Formatting.Indented;
            //settings.NullValueHandling = NullValueHandling.Ignore;

            //retValue = JsonConvert.SerializeObject(m_fields, settings);

            //retValue = FormlyHelper.Serialize(m_fields);
            retValue = FormlyHelper.Serialize(m_fields, new List<JsonConverter> { new EventsConverter() });

            return retValue;
        }

        [HttpGet]
        public string[] LoadFields(string id)
        {
            string[] retValue = new string[2] { string.Empty, string.Empty };

            Employee obj = null;
            using (EmployeeFacade m_dc = EmployeeFacade.Create())
            {
                ReturnValue<Employee> m_objs = m_dc.Get(id);
                if (m_objs.HasValue)
                {
                    obj = m_objs.Value;
                }
            }

            if (obj != null)
            {
                var m_fields = FormlyHelper.ToFormly<EmployeeMetadata>(typeof(EmployeeMetadata));

                JsonSerializerSettings settings = new JsonSerializerSettings();
                settings.ContractResolver = new NullToEmptyListResolver();
                settings.Converters = new List<JsonConverter> { 
                    new Newtonsoft.Json.Converters.StringEnumConverter { CamelCaseText = false }
                };

                settings.Formatting = Formatting.Indented;
                settings.NullValueHandling = NullValueHandling.Ignore;

                retValue[0] = JsonConvert.SerializeObject(m_fields, settings);

                retValue[1] = JsonConvert.SerializeObject(obj);
            }
            else
            {
            }

            //
            return retValue;
        }

        [HttpPost]
        public System.Net.Http.HttpResponseMessage Add(JObject data)
        {
            System.Net.Http.HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.OK);

            return retValue;
        }

        [HttpPost]
        public System.Net.Http.HttpResponseMessage Load(DTParameters data)
        {
            System.Net.Http.HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.BadRequest);

            using (EmployeeFacade m_dc = EmployeeFacade.Create())
            {
                ReturnValue<IQueryable<Employee>> m_objs = m_dc.GetAll();

                DTResult<Employee> result = DTResult<Employee>.Empty("Nessun elemento trovato");
                if (m_objs.HasValue)
                {
                    EmployeesResultSet m_rs = new EmployeesResultSet(data, m_objs.Value);
                    result = m_rs.GetResult();
                }
                else
                {
                    if (m_objs.HasError)
                    {
                        result.Message.MessageType = MessageTypes.Error;
                        result.Message.Message = m_objs.Error.Message;
                    }
                }

                retValue = Request.CreateResponse(HttpStatusCode.OK, result);
            }

            return retValue;
        }

        [HttpPost]
        public async Task<HttpResponseMessage> Upload()
        {
            HttpResponseMessage retValue = null;

            try
            {
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                var root = HttpContext.Current.Server.MapPath("~/AppData/Temp/FileUploads");
                Directory.CreateDirectory(root);
                var provider = new MultipartFormDataStreamProvider(root);
                
                var result = await Request.Content.ReadAsMultipartAsync(provider);
                if (result.FormData["model"] == null)
                {
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
                }

                var model = result.FormData["model"];
                //TODO: Do something with the json model which is currently a string
                JObject obj = JObject.Parse(model.ToString());
                dynamic json = obj;
                DateTime m_data = DateTime.Parse(json.DataAvvenimento.ToString());
                FileUploaded m_file = JsonConvert.DeserializeObject<FileUploaded>(json.FotoArticolo.ToString());

                var m_Folder = HttpContext.Current.Server.MapPath(string.Format("~/{0}", m_file.Folder));

                //get the files
                List<MultipartFileData> m_fileData = new List<MultipartFileData>();
                foreach (var file in result.FileData)
                {
                    //TODO: Do something with each uploaded file
                    if (string.IsNullOrEmpty(file.Headers.ContentDisposition.FileName))
                    {
                        return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
                    }
                    string fileName = file.Headers.ContentDisposition.FileName;
                    if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                    {
                        fileName = fileName.Trim('"');
                    }
                    if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                    {
                        fileName = Path.GetFileName(fileName);
                    }

                    m_fileData.Add(file);

                    string m_fileName = string.Format("{0}/{1}", m_Folder, fileName);
                    byte[] documentData;
                    documentData = File.ReadAllBytes(file.LocalFileName);
                    File.WriteAllBytes(m_fileName, documentData); // Requires System.IO


                    //File.Move(file.LocalFileName, Path.Combine(root, fileName));
                }

                retValue = Request.CreateResponse(HttpStatusCode.OK, "success!");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return retValue;
        }

        [HttpPost]
        public async Task<string> Upload_old()
        {
            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            // extract file name and file contents
            var fileNameParam = provider.Contents[0].Headers.ContentDisposition.Parameters
                .FirstOrDefault(p => p.Name.ToLower() == "filename");
            string fileName = (fileNameParam == null) ? "" : fileNameParam.Value.Trim('"');
            byte[] file = await provider.Contents[0].ReadAsByteArrayAsync();

            // Here you can use EF with an entity with a byte[] property, or
            // an stored procedure with a varbinary parameter to insert the
            // data into the DB

            var result = string.Format("Received '{0}' with length: {1}", fileName, file.Length);
            return result;
        }

        [HttpPost]
        public HttpResponseMessage SendData(JObject param)
        {
            HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.BadRequest);








            return retValue;
        }

        [HttpPost]
        public HttpResponseMessage CambioData(JObject param)
        {
            HttpResponseMessage retValue = new HttpResponseMessage(HttpStatusCode.BadRequest);

            dynamic json = param;

            ImageField m_image = json.FotoProdotto.ToObject<ImageField>();
            string m_lastName = json.LastName;
            string m_firstName = json.FirstName;
            string m_id = json.EmployeeId;

            m_image.Save();

            //string filePath = string.Format(@"{0}\{1}", HttpContext.Current.Server.MapPath(m_image.FolderName), m_image.Filename);
            //System.IO.File.WriteAllBytes(filePath, Convert.FromBase64String(m_image.Base64));

            Console.WriteLine("{0}, {1}, {2}", m_lastName, m_firstName, m_id);

            return retValue;
        }

        private string GetDeserializedFileName(MultipartFileData fileData)
        {
            var fileName = GetFileName(fileData);
            return JsonConvert.DeserializeObject(fileName).ToString();
        }

        public string GetFileName(MultipartFileData fileData)
        {
            return fileData.Headers.ContentDisposition.FileName;
        }
    }
}